package com.vote.www.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.vote.www.core.quartz.AppMap;
import com.vote.www.domain.Czjuserapprove;
import com.vote.www.domain.Czjuserinfo;
import com.vote.www.domain.Czjusermess;
import com.vote.www.service.CzjuserapproveService;
import com.vote.www.service.CzjuserinfoService;
import com.vote.www.service.CzjusermessService;
import com.vote.www.utils.ImgBase64Util;
import com.vote.www.utils.SendMessageUtil;
import com.vote.www.utils.UUIDUtils;

@Controller
public class CzjuserinfoController extends BaseController {

	private static final Logger log = LoggerFactory
			.getLogger(CzjuserinfoController.class);
	
	private static final Integer MAXUPLOAD_SIZE=52428800;//上传头像最大为50兆

	// 登陆
	@RequestMapping("login.do")
	public void login(@RequestParam(required = true) String telephone,
			@RequestParam(required = true) String password,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {

		try {

			Czjuserinfo czjuserinfo = czjuserinfoService
					.loginUserInfo(telephone.trim());
			if (null != czjuserinfo && !"".equals(czjuserinfo)) {
				Map<String, Object> result = new HashMap<String, Object>();
				String pwd = czjuserinfo.getPassword();
				if (StringUtils.isNotBlank(pwd)) {

					if (pwd.equals(password.trim())) {
						// 查询是否已完善资料 1已完善 2未完善
						/*
						 * Map<String, Object> map=new HashMap<String,
						 * Object>(); map.put("userinfoId",czjuserinfo.getId());
						 */
						// List<Czjusermess>
						// czjusermess=czjusermessService.findCzjusermess(map);
						Czjuserapprove czjuserapprove = czjuserapproveService
								.getNew(czjuserinfo.getId());
						String isOk = "0";
						Integer ext3 = 0;
						if (null != czjuserapprove
								&& !"".equals(czjuserapprove)) {
							isOk = "1";
							ext3 = czjuserapprove.getApproveStatus();
						}
						result.put("userId", czjuserinfo.getId());
						result.put("isOk", isOk);
						result.put("ext3", ext3);
						jsonResult(1, "103", "登陆成功", result, response);
						return;
					} else {
						jsonResult(0, "104", "密码错误", result, response);
						return;
					}
				} else {
					jsonResult(0, "105", "用户密码为空", result, response);
					return;
				}

			} else {
				jsonResult(0, "102", "手机号码不存在，尚未注册", "", response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("登陆异常", e);
			jsonResult(0, "101", "登陆异常", "", response);

		}

	}

	// 注册
	@RequestMapping("register.do")
	public void register(Czjuserinfo czjuserinfo,
			@RequestParam(required = true) String pid,
			@RequestParam(required = true) String code,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session, ModelMap model) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();

		if (StringUtils.isBlank(czjuserinfo.getTelephone())) {
			jsonResult(0, "106", "手机号码不能为空", "", response);
			return;
		}
		if (StringUtils.isBlank(czjuserinfo.getPassword())) {
			jsonResult(0, "105", "用户密码为空", result, response);
			return;
		}
		try {

			// 判断手机号码是否已经注册
			Czjuserinfo cinfo = czjuserinfoService.loginUserInfo(czjuserinfo
					.getTelephone());
			if (null != cinfo) {
				jsonResult(0, "108", "手机号码已经注册", result, response);
				return;
			}

			// 校验短信验证的时效 和 对错
			if (AppMap.getVcode(request.getParameter("pid")) == null) {
				jsonResult(0, "110", "验证码失效", result, response);
				return;
			}
			if (!request.getParameter("code").equals(
					AppMap.getVcode(request.getParameter("pid")))) {
				jsonResult(0, "110", "验证码不正确", result, response);
				return;
			}
			//
			czjuserinfo.setType(0); // 用户类型
			czjuserinfo.setCreatetime(new Date());
			czjuserinfo.setEnable("Y");
			czjuserinfo.setIsdelete("0");
			czjuserinfo.setIdentity("0");
			czjuserinfoService.insertCzjuserinfoByAuto(czjuserinfo);
			int lastInsertId = czjuserinfoService.findlastInsert();
			result.put("userId", lastInsertId);

			jsonResult(1, "108", "注册成功", result, response);
		} catch (Exception e) {
			e.printStackTrace();
			log.info("注册用户异常", e);
			jsonResult(0, "107", "系统异常", "", response);

		}

	}

	/**
	 * 此方法已废弃 陈赢 2017年4月28日09:16:16 注释掉 完善个人你信息 方法名：registerNext 创建人：RUI
	 * 时间：2017年4月19日-下午5:22:16
	 * 
	 * @param czjusermess
	 * @param multipartFiles
	 * @param request
	 * @param response
	 * @param session
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	/*
	 * @RequestMapping("registerNext.do") public void registerNext( Czjusermess
	 * czjusermess,
	 * 
	 * @RequestParam(value = "file", required = false) MultipartFile
	 * multipartFiles, HttpServletRequest request, HttpServletResponse response,
	 * HttpSession session, ModelMap model) throws Exception { Map<String,
	 * Object> result = new HashMap<String, Object>();
	 * 
	 * try {
	 * 
	 * String id=request.getParameter("userId"); if (null == id ||
	 * "".equals(id)) { jsonResult(0, "111", "用户为空", "", response); return ; }
	 * //判断用户是否存在 Map<String,Object> map=new HashMap<String, Object>();
	 * map.put("id", id); Czjuserinfo
	 * czjuserinfo=czjuserinfoService.findUserExits(map); if(null==czjuserinfo
	 * ||"".equals(czjuserinfo)){ jsonResult(0, "112", "用户不存在", "", response);
	 * return ; } //复制照片 String pathRoot =
	 * request.getSession().getServletContext() .getRealPath(""); String path =
	 * ""; // 头像 if (!multipartFiles.isEmpty()) { String uuid =
	 * UUID.randomUUID().toString().replaceAll("-", ""); //
	 * 获得文件类型（可以判断如果不是图片，禁止上传） String contentType =
	 * multipartFiles.getContentType(); // 获得文件后缀名称 String imageName =
	 * contentType.substring(contentType .indexOf("/") + 1); path = "/upload/" +
	 * uuid + "." + "jpg"; File file = new File(pathRoot + "/upload"); if
	 * (!file.exists()) { file.mkdir(); } multipartFiles.transferTo(new
	 * File(pathRoot + path));
	 * 
	 * } czjusermess.setPicPath(path);
	 * czjusermess.setUserinfoId(Integer.valueOf(id));
	 * czjusermessService.insertCzjusermess(czjusermess); result.put("userId",
	 * id); jsonResult(1, "112", "个人信息完善成功", result, response); } catch
	 * (Exception e) { e.printStackTrace(); jsonResult(0, "107", "系统异常", "",
	 * response); }
	 * 
	 * }
	 */

	/**
	 *
	 * 方法名：sendMSM 创建人：RUI 时间：2017年5月2日-上午9:31:58
	 * 
	 * @param pid
	 * @param telephone
	 * @param type
	 *            1注册验证码 2审核通过验证码 3审核不通过验证码 4忘记密码验证码
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("sendMSM.do")
	public void sendMSM(@RequestParam(required = true) String pid,
			@RequestParam(required = true) String telephone,
			@RequestParam(required = true) String type,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {

		try {
			HashMap<String, Object> result = SendMessageUtil.send(telephone,
					response, request, type);

			if ("000000".equals(result.get("statusCode"))) {
				String ranStr = (String) result.get("ranStr");// 验证码
				String pp = UUIDUtils.getUUID();
				AppMap.setVcode(ranStr, pp);
				result.put("pp", pp);

				jsonResult(1, "109", "短信发送成功", result, response);
			} else {
				/*
				 * 异常返回输出错误码和错误信息 System.out.println("错误码=" +
				 * result.get("statusCode") + " 错误信息= " +
				 * result.get("statusMsg"));
				 */
				jsonResult(0, "110", "短信发送失败", result, response);

			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("获取验证码出错", e);
		}

	}

	/**
	 * 完善个人资料 方法名：registerNext1 创建人：RUI 时间：2017年5月2日-上午8:54:18
	 * 
	 * @param czjusermess
	 * @param file
	 * @param request
	 * @param response
	 * @param session
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("registerNext1.do")
	public void registerNext1(
			Czjusermess czjusermess,
			@RequestParam(required = false) String file,
			@RequestParam(value = "vo", required = false) MultipartFile videoFile,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session, ModelMap model) throws Exception {
		

		try {
			// String file = ImgBase64Util.getImageStr("D:/a/1.jpg");//读取D盘
			Map<String, Object> result = new HashMap<String, Object>();
			String id = request.getParameter("userId");
			if (null == id || "".equals(id)) {
				jsonResult(0, "111", "用户为空", "", response);
				return;
			}
			// 判断用户是否存在
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", id);
			Czjuserinfo czjuserinfo = czjuserinfoService.findUserExits(map);
			if (null == czjuserinfo || "".equals(czjuserinfo)) {
				jsonResult(0, "112", "用户不存在", "", response);
				return;
			}
			Map<String, Object> messMap = new HashMap<String, Object>();
			messMap.put("userinfoId", id);
			List<Czjusermess> c = czjusermessService.findUserExits1(messMap);
			if (null != c && c.size() > 0) {
				czjusermessService.deleteCzjusermess(c);
			}
			String pathRoot = request.getSession().getServletContext()
					.getRealPath("");
			String picName = UUIDUtils.getDateUUID();
			String path = "/upload/" + picName + ".jpg";// 数据库保存路径
			boolean isTrue = ImgBase64Util.generateImage(file, pathRoot + path);
			if (isTrue == false) {
				jsonResult(0, "120", "转存头像失败", "", response);
				return;
			}
			// 新增视频begin
			if (videoFile!=null) {
				String contentType = videoFile.getContentType();
				String voideType = contentType
                        .substring(contentType.indexOf("/") + 1);

				if (!videoFile.isEmpty() && videoFile.getSize() > 0) {
                    if(videoFile.getSize()>MAXUPLOAD_SIZE){
                        jsonResult(0, "114", "视频大小不能大于50M",
                                result, response);
                        return;
                    }
                    boolean type = volidateVodeType(voideType);
                    if (type == false) {
                        jsonResult(0, "112", "上传的视频类型错误，上传的类型只能是 mp4 rmvb avi mov",
                                result, response);
                        return;
                    }
                    String videoPath =null;
                    if(voideType.equalsIgnoreCase("quicktime")){
                    	
                    	videoPath = "/video/" + videoFile.getOriginalFilename();
                    }else{
                    	videoPath = "/video/" + UUIDUtils.getUUID() + "."
                                + voideType;
                    }
     
                    File fileDir = new File(pathRoot + "/video");
                    if (!fileDir.exists()) {
                        fileDir.mkdir();
                    }
                    videoFile.transferTo(new File(pathRoot + videoPath));
                    czjusermess.setExt2(videoPath);
                }else{
                    czjusermess.setVodeoUri(null);
                }
			}
			// end
			czjusermess.setPicPath(path);
			czjusermess.setUserinfoId(Integer.valueOf(id));
			czjusermess.setExt3(0);
			czjusermessService.insertCzjusermess(czjusermess);
			result.put("userId", id);
			result.put("ext3", 0);
			// by tangwj
			czjuserapproveService.aotoUpdate(Integer.parseInt(id));

			jsonResult(1, "112", "个人信息完善成功", result, response);
		} catch (Exception e) {
			e.printStackTrace();
			log.info("完善个人信息出错", e);
			jsonResult(0, "107", "系统异常", "", response);
		}

	}

	/**
	 * 忘记密码 方法名：forgotPwd 创建人：RUI 时间：2017年5月2日08:55:57
	 * 
	 * @param czjusermess
	 * @param file
	 * @param request
	 * @param response
	 * @param session
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("forgotPwd.do")
	public void forgotPwd(@RequestParam(required = true) String phone,
			@RequestParam(required = true) String password,
			@RequestParam(required = true) String code,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session, ModelMap model) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();

		try {

			// 校验短信验证的时效 和 对错
			if (AppMap.getVcode(request.getParameter("pid")) == null) {
				jsonResult(0, "110", "验证码失效", result, response);
				return;
			}
			if (!request.getParameter("code").equals(
					AppMap.getVcode(request.getParameter("pid")))) {
				jsonResult(0, "110", "验证码不正确", result, response);
				return;
			}
			// 修改密码
			Czjuserinfo czjuserinfo = new Czjuserinfo();
			czjuserinfo.setPassword(password);
			czjuserinfo.setTelephone(phone);
			czjuserinfoService.updatePwdByPhone(czjuserinfo);
			jsonResult(1, "121", "修改密码成功", result, response);
		} catch (Exception e) {
			e.printStackTrace();
			log.info("修改密码异常", e);
			jsonResult(0, "107", "系统异常", "", response);
		}

	}

	public boolean volidateVodeType(String type) {
		if (type.equalsIgnoreCase("mp4") || type.equalsIgnoreCase("avi")
				|| type.equalsIgnoreCase("rmvb") || type.equalsIgnoreCase("quicktime"))
			return true;
		else
			return false;
	}

	@Resource
	private CzjuserinfoService czjuserinfoService;
	@Resource
	private CzjusermessService czjusermessService;
	@Resource
	private CzjuserapproveService czjuserapproveService;

}